package com.sinodata.bsm.center.web.action.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.CollectTaskBean;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.DataTypeCache;
import com.sinodata.bsm.center.cache.PropertyCache;
import com.sinodata.bsm.center.cache.RelationTypeCache;
import com.sinodata.bsm.center.cache.ResFindDefCache;
import com.sinodata.bsm.center.service.event.EventTypeService;
import com.sinodata.bsm.center.service.probe.ProbeService;
import com.sinodata.bsm.center.service.resource.CollectTaskService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.center.service.resource.ResTypeService;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.vo.Attribute;
import com.sinodata.bsm.common.vo.CollectField;
import com.sinodata.bsm.common.vo.CollectParam;
import com.sinodata.bsm.common.vo.CollectTask;
import com.sinodata.bsm.common.vo.Collector;
import com.sinodata.bsm.common.vo.DataType;
import com.sinodata.bsm.common.vo.EventType;
import com.sinodata.bsm.common.vo.MotiRestypeRel;
import com.sinodata.bsm.common.vo.Probe;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.RelationType;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResAttrVal;
import com.sinodata.bsm.common.vo.ResFindDef;
import com.sinodata.bsm.common.vo.ResType;

public class ResTypeAction extends BaseAction<ResType> {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private File upload;
    private String uploadFileName;
    private ResType entity;
    private Long id;
    @Autowired
    private ResTypeService resTypeService;
    @Autowired
    private DataTypeCache dataTypeCache;
    @Autowired
    private PropertyCache propertyCache;
    @Autowired
    private EventTypeService eventTypeService;
    @Autowired
    private CollectTaskService collectTaskService;
    @Autowired
    private ResFindDefCache resFindDefCache;

    public static final String TYPE_RESTYPE_NODE = "RESTYPE";
    public static final String TYPE_ATTRIBUTE_NODE = "ATTRIBUTE";
    public static final String TYPE_PROPERTY_NODE = "PROPERTY";
    public static final String TYPE_OTHER_NODE = "OTHER";

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 生成子类别的节点并生成指标和属性节点
     * 
     * @param map
     * @param parent
     * @return
     */
    private JSONObject makeAttPropNode(Map<Long, List<ResType>> map, ResType parent) {
        Long pId = parent.getId();
        List<ResType> ctypes = map.get(pId);
        JSONObject json = new JSONObject();
        json.element("id", pId);
        json.element("name", parent.getName());
        json.element("parentId", parent.getParentId());
        //json.element("icon", parent.getIcon());
        json.element("type", TYPE_RESTYPE_NODE);
        JSONArray jsonArray = new JSONArray();
        if (ctypes != null && ctypes.size() > 0) {
            for (ResType t : ctypes) {
                jsonArray.add(makeAttPropNode(map, t));
            }
        }
        // //////////////////////////////////本资源类型属性节点

        JSONObject attrjson = new JSONObject();
        attrjson.element("name", "属性");
        attrjson.element("type", TYPE_OTHER_NODE);
        JSONArray attrjsonArray = new JSONArray();
        ResTypeBean bean = ResTypeBean.get(pId.longValue());
        List<Attribute> attList = bean.attributes(false);
        if (attList != null) {
            for (Attribute att : attList) {
                JSONObject tmpjson = new JSONObject();
                tmpjson.element("id", att.getId());
                tmpjson.element("name", att.getName());
                tmpjson.element("dataUnit", att.getDataUnit());
                tmpjson.element("resType", att.getResType());
                tmpjson.element("dataTypeId", att.getDataTypeId());
                DataType dt = dataTypeCache.get(att.getDataTypeId());
                tmpjson.element("dataTypeName", dt.getName());
                tmpjson.element("type", TYPE_ATTRIBUTE_NODE);
                attrjsonArray.add(tmpjson);
            }
        }
        attrjson.element("children", attrjsonArray);

        // //////////////////////////////////////////////////////本资源的指标节点
        JSONObject propjson = new JSONObject();
        propjson.element("name", "指标");
        propjson.element("type", TYPE_OTHER_NODE);
        JSONArray propjsonArray = new JSONArray();

        List<Property> propList = bean.properties(false);
        if (propList != null) {
            for (Property prop : propList) {
                JSONObject tmpjson = new JSONObject();
                tmpjson.element("id", prop.getId());
                tmpjson.element("name", prop.getName());
                tmpjson.element("dataUnit", prop.getDataUnit());
                tmpjson.element("resType", prop.getResType());
                tmpjson.element("dataTypeId", prop.getDataTypeId());
                // DataType dt = dataTypeCache.get(prop.getDataTypeId());
                // tmpjson.element("dataTypeName", dt.getName());
                tmpjson.element("type", TYPE_PROPERTY_NODE);
                propjsonArray.add(tmpjson);
            }
        }
        propjson.element("children", propjsonArray);
        // //////////////////////////////////////////////////
        jsonArray.add(attrjson);
        jsonArray.add(propjson);
        json.element("children", jsonArray);
        return json;
    }

    /**
     * 按资源模型树生成属性和指标
     * 
     * @return
     * @throws Exception
     */
    public String propertyTree() throws Exception {
        List<ResType> types = resTypeService.getAll();
        Collections.sort(types);
        Map<Long, List<ResType>> map = new LinkedHashMap<Long, List<ResType>>();
        List<ResType> roots = new ArrayList<ResType>();
        for (ResType t : types) {
            List<ResType> list = null;
            if (t.getParentId() == null) {
                roots.add(t);
            }
            if (!map.containsKey(t.getId().longValue())) {
                list = new ArrayList<ResType>();
                map.put(t.getId(), list);
            }
            if (t.getParentId() != null) {
                map.get(t.getParentId().longValue()).add(t);
            }
        }
        JSONArray jsonArray = new JSONArray();
        for (ResType t : roots) {
            jsonArray.add(makeAttPropNode(map, t));
        }
        Struts2Utils.renderText(jsonArray.toString());
        return null;
    }

    /**
     * 递归生成子资源模型
     * 
     * @param map
     * @param parent
     * @return
     */
    private JSONObject makeChildren(Map<Long, List<ResType>> map, ResType parent) {
        Long pId = parent.getId();
        List<ResType> ctypes = map.get(pId);
        JSONObject json = new JSONObject();
        json.element("id", pId);
        json.element("name", parent.getName());
        json.element("parentId", parent.getParentId());
        //json.element("icon", parent.getIcon());

        // 资源发现程序
        ResFindDefCache resFindDefCache = SpringContextHolder.getBean(ResFindDefCache.class);
        ResFindDef resFindDef = resFindDefCache.getForResType(parent.getId());

        json.element("selfFound", resFindDef == null ? 0 : 1);
        JSONArray jsonArray = new JSONArray();
        if (ctypes != null && ctypes.size() > 0) {
            for (ResType t : ctypes) {
                jsonArray.add(makeChildren(map, t));
            }
        }
        json.element("children", jsonArray);
        return json;
    }

    /**
     * 资源模型树
     * 
     * @return
     * @throws Exception
     */
    public String typeTree() throws Exception {
        List<ResType> types = resTypeService.getAll();
        //是否显示不可手动添加
        Object isFind = Struts2Utils.getParameter("isDisplayFind");

        Collections.sort(types);
        Map<Long, List<ResType>> map = new LinkedHashMap<Long, List<ResType>>();
        List<ResType> roots = new ArrayList<ResType>();
        for (ResType t : types) {

            //如果可手动添加 (用于构建资源新增树)
            if (isFind != null && t.getAddFlag().intValue() == 0) {
                continue;
            }

            List<ResType> list = null;
            if (t.getParentId() == null) {
                roots.add(t);
            }
            if (!map.containsKey(t.getId().longValue())) {
                list = new ArrayList<ResType>();
                map.put(t.getId().longValue(), list);
            }

            if (t.getParentId() != null) {
                map.get(t.getParentId().longValue()).add(t);
            }
        }
        JSONArray jsonArray = new JSONArray();
        for (ResType t : roots) {
            jsonArray.add(makeChildren(map, t));
        }
        Struts2Utils.renderText(jsonArray.toString());
        return null;
    }

    public String findAttribute() throws Exception {
        ResTypeBean bean = ResTypeBean.get(id);
        List<Attribute> attList = bean.attributes();
        Struts2Utils.renderJson(attList);
        return null;
    }

    @Override
    public String list() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new ResType();
        } else {
            entity = resTypeService.get(id);
        }

    }

    @Override
    public String save() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResType getModel() {
        // TODO Auto-generated method stub
        return entity;
    }

    public String frame() {
        return "frame";
    }

    public String model() {
        id = id == null ? 1101020000000L : id;
        ResType resType = resTypeService.get(id);

        // 资源发现程序
        ResFindDefCache resFindDefCache = SpringContextHolder.getBean(ResFindDefCache.class);
        ResFindDef resFindDef = resFindDefCache.getForResType(resType.getId());

        List<ResType> resTypes = resTypeService.getAll();
        List<ResType> parentRestype = new ArrayList<ResType>(); // 所属继承关系
        ResType tempEntity = resType;
        for (int i = 0; resTypes != null && i < resTypes.size(); i++) {
            ResType entity = resTypes.get(i);
            if (tempEntity.getParentId() != null && tempEntity.getParentId().equals(entity.getId())) {
                parentRestype.add(entity);
                tempEntity = entity;
                i = 0;
            }
        }
        Collections.sort(parentRestype);
        List<ResType> childs = new ArrayList<ResType>(); // 子类别
        for (int i = 0; i < resTypes.size(); i++) {
            ResType entity = resTypes.get(i);
            if (entity.getParentId() != null && entity.getParentId().equals(id)) {
                childs.add(entity);
            }
        }
        Collections.sort(childs);

        ResTypeBean bean = ResTypeBean.get(id);

        // 属性信息
        List<Attribute> attributes = bean == null ? new ArrayList<Attribute>() : bean.attributes();
        JSONArray attributeArray = new JSONArray();
        for (int i = 0; attributes != null && i < attributes.size(); i++) {
            Attribute attribute = attributes.get(i);
            JSONObject object = new JSONObject();
            object.element("id", attribute.getId());
            object.element("code", attribute.getCode() == null ? "" : attribute.getCode());
            object.element("name", attribute.getName());
            object.element("resType", attribute.getResType());
            ResType t = resTypeService.get(attribute.getResType());
            object.element("resTypeName", t.getName());
            object.element("dataTypeId", attribute.getDataTypeId());
            DataType dt = dataTypeCache.get(attribute.getDataTypeId());
            object.element("dataTypeName", dt == null ? "" : dt.getName());
            object.element("dataUnit", attribute.getDataUnit() == null ? "" : attribute.getDataUnit());
            object.element("desc", attribute.getDesc() == null ? "" : attribute.getDesc());
            attributeArray.add(object);
        }

        // 指标信息
        List<Property> propertys = bean == null ? new ArrayList<Property>() : bean.properties();

        Collections.sort(propertys, new CompareProperty());
        JSONArray propertyArray = new JSONArray();
        for (int i = 0; propertys != null && i < propertys.size(); i++) {
            Property property = propertys.get(i);
            JSONObject object = new JSONObject();
            object.element("id", property.getId());
            Boolean isCollect = false; //判断是否采集
            List<CollectTask> collctTasks = collectTaskService.findByResTypeId(id);
            for (CollectTask collectTask : collctTasks == null ? collctTasks = new ArrayList<CollectTask>() : collctTasks) {
                CollectTaskBean taskBean = CollectTaskBean.get(collectTask.getId());
                List<CollectField> collectFields = taskBean.getCollectField();
                Boolean isHave = false;
                for (CollectField collectField : collectFields == null ? collectFields = new ArrayList<CollectField>() : collectFields) {
                    if (collectField.getProp().longValue() == property.getId().longValue()) {
                        isCollect = true;
                        isHave = true;
                        break;
                    }
                }

                if (isHave == true) {
                    break;
                }
            }

            object.element("isCollect", isCollect == false ? "否" : "是");
            object.element("code", property.getCode() == null ? "" : property.getCode());
            object.element("name", property.getName());
            ResType t = resTypeService.get(property.getResType());
            object.element("resTypeName", t.getName());
            object.element("resType", property.getResType());
            object.element("dataTypeId", property.getDataTypeId());
            DataType dt = dataTypeCache.get(property.getDataTypeId());
            object.element("dataTypeName", dt == null ? "" : dt.getName());
            object.element("dataUnit", property.getDataUnit() == null ? "" : property.getDataUnit());
            object.element("store", property.getStore());
            object.element("display", property.getDisplay());
            object.element("isCalc", property.getIsCalc() == null ? "" : property.getIsCalc());
            object.element("calcExpr", property.getCalcExpr() == null ? "" : property.getCalcExpr());
            propertyArray.add(object);
        }

        //事件定义
        List<EventType> eventTypes = bean == null ? new ArrayList<EventType>() : bean.eventType();
        JSONArray eventTypeArray = new JSONArray();
        for (int i = 0; eventTypes != null && i < eventTypes.size(); i++) {
            EventType eventType = eventTypes.get(i);
            JSONObject object = new JSONObject();
            object.element("id", eventType.getId());
            object.element("name", eventType.getName());
            ResType t = eventType.getResTypeId() == null ? null : resTypeService.get(eventType.getResTypeId());
            object.element("resName", t == null ? "" : t.getName());
            object.element("isRecoverable", eventType.getRecoverable().intValue() == EventConstants.TYPE_RECOVERABLE ? "可恢复" : "不可恢复");
            object.element("desc", eventType.getDesc() == null ? "" : eventType.getDesc());
            object.element("expr", eventType.getExpr() == null ? "" : eventType.getExpr());
            object.element("msg", eventType.getMsg() == null ? "" : eventType.getMsg());
            eventTypeArray.add(object);
        }

        // 采集模板
        List<CollectTask> collctTasks = collectTaskService.findByResTypeId(id);
        JSONArray collectTaskArray = new JSONArray();
        for (int i = 0; collctTasks != null && i < collctTasks.size(); i++) {
            CollectTask collectTask = collctTasks.get(i);
            JSONObject object = new JSONObject();
            object.element("id", collectTask.getId());
            ResType r = resTypeService.get(collectTask.getResTypeId());
            object.element("resTypeId", collectTask.getResTypeId());
            object.element("resTypeName", r.getName());

            CollectTaskBean taskBean = CollectTaskBean.get(collectTask.getId());
            Collector collector = taskBean.getCollector();
            object.element("collectorId", collector == null ? "" : collector.getId());
            object.element("className", collector == null ? "" : collector.getClassName().replace("com.sinodata.bsm.cicp.collector.", ""));

            List<CollectParam> collectParams = taskBean.getCollectParam();
            StringBuilder paramsBuilder = new StringBuilder("");
            if (collectParams != null)
                for (CollectParam collectParam : collectParams) {
                    paramsBuilder.append(collectParam.getId() + ":" + collectParam.getParamName() + ":" + collectParam.getParamValue() + "</br>");
                }
            // 采集参数
            object.element("collectParam", paramsBuilder.toString());
            // 指标映射
            List<CollectField> collectFields = taskBean.getCollectField();
            StringBuilder fieldBuilder = new StringBuilder("");
            if (collectFields != null) {
                for (CollectField collectField : collectFields) {
                    Property property = propertyCache.get(collectField.getProp());
                    if (property != null) {
                        fieldBuilder.append(property.getId() + ":" + property.getName() + ":" + collectField.getFieldName() + "</br>");
                    }
                }
            }
            object.element("collectField", fieldBuilder.toString());
            collectTaskArray.add(object);
        }

        Struts2Utils.setRequestAttribute("childResTypes", childs);
        Struts2Utils.setRequestAttribute("resFindDef", resFindDef);
        Struts2Utils.setRequestAttribute("resType", resType);
        Struts2Utils.setRequestAttribute("parents", parentRestype);
        Struts2Utils.setRequestAttribute("attributes", attributeArray);
        Struts2Utils.setRequestAttribute("propertys", propertyArray);
        String collector = resFindDef == null ? "" : resFindDef.getCollector().replace("com.sinodata.bsm.cicp.", "");
        Struts2Utils.setRequestAttribute("className", collector.indexOf(",") == -1 ? collector : collector.substring(0, collector.indexOf(",")));
        Struts2Utils.setRequestAttribute("childResTypes", childs);
        Struts2Utils.setRequestAttribute("collectTask", collectTaskArray);
        Struts2Utils.setRequestAttribute("eventTypes", eventTypeArray);
        return "model";
    }

    //导入资源页面
    public String resImport() {
        Struts2Utils.setRequestAttribute("resId", Struts2Utils.getParameter("resId"));
        Struts2Utils.setRequestAttribute("viewId", Struts2Utils.getParameter("viewId"));
        return "import";
    }

    //导出模板
    public String excuteExport() throws Exception {
        try {
            ResTypeBean bean = ResTypeBean.get(id);
            ResType type = bean.resType();
            List<Attribute> attList = bean.attributes();

            String fileName = type.getName();
            String displayFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            response.setContentType("APPLICATION/msexcel; charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + displayFileName.trim().replaceAll("\\s", "") + ".xls\"");

            HSSFWorkbook workBook = new HSSFWorkbook();
            HSSFSheet sheet = workBook.createSheet(fileName.trim().replaceAll("\\s", ""));
            sheet.setColumnWidth(0, 6000);
            sheet.setColumnWidth(1, 6000);
            sheet.setColumnWidth(2, 5000);
            sheet.setColumnWidth(3, 5000);
            for (int i = 0; attList != null && i < attList.size(); i++) {
                sheet.setColumnWidth((i + 4), 6000);
            }
            sheet.setColumnWidth(attList == null ? 4 : attList.size() + 4, 7000);

            //提示(合并)
            sheet.addMergedRegion(new CellRangeAddress(1, 6, 0, (5 + (attList.size() - 1))));

            //创建资源类型
            HSSFRow resTypeRow = sheet.createRow(0);
            HSSFCell resTypeIdCell = resTypeRow.createCell(0);
            resTypeIdCell.setCellValue(new HSSFRichTextString("资源类别ID:" + id));

            HSSFRow promptRow = sheet.createRow(1);
            HSSFCell promptValue = promptRow.createCell(0);

            HSSFCellStyle promptStyle = workBook.createCellStyle();
            HSSFFont promptFont = workBook.createFont();
            promptFont.setColor(HSSFFont.COLOR_RED);
            promptStyle.setFont(promptFont);
            promptStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_GENERAL);
            promptStyle.setWrapText(true);
            promptValue.setCellStyle(promptStyle);

            StringBuffer promptBuffer = new StringBuffer("注释(请选择对应的数值编号):\r\n");

            promptBuffer.append("监控代理：");
            ProbeService probeService = SpringContextHolder.getBean(ProbeService.class);
            List<Probe> probeList = probeService.findAllProbe();
            for (int i = 0; probeList != null && i < probeList.size(); i++) {
                Probe probe = probeList.get(i);
                promptBuffer.append(probe.getId() + "." + probe.getName() + " ");
                if (i % 9 == 0 && i != 0) {
                    promptBuffer.append("\r\n");
                }
            }

            promptBuffer.append("\r\n");
            promptBuffer.append("与父资源关系：");
            List<RelationType> relationList = SpringContextHolder.getBean(RelationTypeCache.class).getAll();
            for (int i = 0; i < relationList.size(); i++) {
                RelationType relationType = relationList.get(i);
                promptBuffer.append(relationType.getId() + "." + relationType.getName() + " ");
            }

            promptValue.setCellValue(new HSSFRichTextString(promptBuffer.toString()));

            HSSFRow attributeRow = sheet.createRow(7);

            //资源名称样式
            HSSFCellStyle attributeStyle = workBook.createCellStyle();
            HSSFFont attributeFont = workBook.createFont();
            attributeFont.setColor(HSSFColor.GREEN.index);
            attributeFont.setFontHeightInPoints((short) 14);
            attributeStyle.setFont(attributeFont);

            HSSFCell resNameCell = attributeRow.createCell(0);
            resNameCell.setCellValue(new HSSFRichTextString("资源名称"));
            resNameCell.setCellStyle(attributeStyle);

            HSSFCell resIpCell = attributeRow.createCell(1);
            resIpCell.setCellValue(new HSSFRichTextString("资源IP"));
            resIpCell.setCellStyle(attributeStyle);

            HSSFCell proxyCell = attributeRow.createCell(2);
            proxyCell.setCellValue(new HSSFRichTextString("监控代理"));
            proxyCell.setCellStyle(attributeStyle);

            HSSFCell relationCell = attributeRow.createCell(3);
            relationCell.setCellValue(new HSSFRichTextString("与父资源关系"));
            relationCell.setCellStyle(attributeStyle);

            for (int i = 0; attList != null && i < attList.size(); i++) {
                Attribute attribute = attList.get(i);
                HSSFCell dynamicCell = attributeRow.createCell((i + 4));
                dynamicCell.setCellValue(new HSSFRichTextString(attribute.getName()));
                dynamicCell.setCellStyle(attributeStyle);
            }

            HSSFCell descCell = attributeRow.createCell(attList == null ? 4 : attList.size() + 4);
            descCell.setCellValue(new HSSFRichTextString("描述"));
            descCell.setCellStyle(attributeStyle);

            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String excuteImport() throws Exception {
        Long parentId = Struts2Utils.getParameter("resId").equals("") ? null : Long.parseLong(Struts2Utils.getParameter("resId"));
        String excuteInfo = "";
        InputStream is = null;
        File toFile = null;
        OutputStream os = null;
        try {

            String savePath = ServletActionContext.getServletContext().getRealPath("/tmp-files");
            is = new FileInputStream(upload);
            int fileSize = (is.available() / 1024); //最大上传1MB
            if (fileSize > 1024) {
                excuteInfo = "模板大小不能大于1M";

            } else {
                String type = uploadFileName.substring(uploadFileName.indexOf("."));
                String name = uploadFileName.substring(0, uploadFileName.indexOf(".")) + System.currentTimeMillis();
                toFile = new File(savePath, name + type);
                os = new FileOutputStream(toFile);
                byte[] buffer = new byte[1024];
                int length = 0;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, buffer.length);
                }
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
            excuteInfo = "资源导入失败！";
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.flush();
                os.close();
            }
        }

        if (toFile != null && toFile.exists()) { // 上传文件已经存在服务器 读取EXCEL
            FileInputStream stream = new FileInputStream(toFile);

            HSSFWorkbook workBook = new HSSFWorkbook(stream);
            HSSFSheet sheet = workBook.getSheetAt(0);

            int rowsCount = sheet.getLastRowNum() - 7; //需要读取的总行数
            int colsCount = sheet.getRow(7).getLastCellNum();
            HSSFCell resTypeCell = sheet.getRow(0).getCell(0); //资源类别
            Long resTypeId = null;
            if (resTypeCell != null) {
                String resTypeCellValue = resTypeCell.getRichStringCellValue().getString();
                resTypeId = Long.parseLong(resTypeCellValue.substring(resTypeCellValue.indexOf(":") + 1));
            }
            if (rowsCount > 0) { //如果有填写资源行 进行资源读取
                String viewId = request.getParameter("viewId");
                String isRoot = request.getParameter("isRoot");
                if (isRoot != null) {
                    parentId = null;
                }

                //导入失败的个数
                int importErrorSum = 0;
                try {
                    StringBuilder resValidate = new StringBuilder("导入完成,请刷新资源树！");
                    ResService resService = SpringContextHolder.getBean(ResService.class);
                    for (int i = 0; i < rowsCount; i++) {
                        HSSFRow resRow = sheet.getRow((i + 8));

                        List<ResAttrVal> attValList = new ArrayList<ResAttrVal>();

                        if (resRow.getCell(0) == null || resRow.getCell(1) == null || resRow.getCell(2) == null || resRow.getCell(3) == null) {
                            importErrorSum++;
                            continue;
                        }

                        //读取单元格
                        String resName = resRow.getCell(0).getRichStringCellValue().getString();
                        String resIp = resRow.getCell(1).getRichStringCellValue().getString();

                        if (!resIp.matches("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b")) {
                            importErrorSum++;
                            continue;
                        }

                        Long probeId = Long.parseLong(String.valueOf((int) resRow.getCell(2).getNumericCellValue()));

                        ProbeService probeService = SpringContextHolder.getBean(ProbeService.class);
                        if (probeService.findById(probeId) == null) {
                            importErrorSum++;
                            continue;
                        }

                        Long resRelId = Long.parseLong(String.valueOf((int) resRow.getCell(3).getNumericCellValue()));
                        if (SpringContextHolder.getBean(RelationTypeCache.class).get(resRelId) == null) {
                            importErrorSum++;
                            continue;
                        }

                        ResTypeBean bean = ResTypeBean.get(resTypeId);
                        List<Attribute> attList = bean.attributes();
                        for (int a = 0; attList != null && a < attList.size(); a++) {
                            Attribute attribute = attList.get(a);
                            //封装ResAttrVal
                            ResAttrVal attval = new ResAttrVal();
                            HSSFCell dynamicCell = resRow.getCell((a + 4));
                            attval.setAttrId(attribute.getId());
                            String attrValue = "";
                            if (dynamicCell != null && dynamicCell.getCellType() == 0) { //如果是numeric 转换成string
                                attrValue = String.valueOf((int) dynamicCell.getNumericCellValue());
                            } else if (dynamicCell != null) {
                                attrValue = dynamicCell.getRichStringCellValue().getString();
                            }
                            attval.setAttrValue(attrValue);
                            attValList.add(attval);
                        }
                        HSSFCell descCell = resRow.getCell(attList == null ? 4 : attList.size() + 4);
                        String desc = "";
                        if (descCell != null) {
                            if (descCell.getCellType() == 0) {
                                desc = String.valueOf((int) descCell.getNumericCellValue());
                            } else {
                                desc = descCell.getRichStringCellValue().getString();
                            }
                        }

                        Res res = new Res();
                        res.setResTypeId(resTypeId);
                        res.setProbeId(probeId);
                        res.setIp(resIp);
                        res.setName(resName);
                        res.setDesc(desc);
                        res.setPaused(ResConstants.RES_NOT_PAUSED);
                        res.setHealthStatus(ResConstants.NORMAL_USABLE);
                        res.setDeleted(0);
                        if (parentId != null) {
                            resService.addResource(parentId, res, attValList, resRelId);
                        } else {
                            resService.addTopResource(Long.parseLong(viewId), res, attValList);
                        }
                    }

                    if (importErrorSum > 0) {
                        resValidate.append("成功导入<span style='color:#ffffff;'>" + (rowsCount - importErrorSum) + "</span>条,失败<span style='color:red;font-weight:bold;'>" + importErrorSum + "</span>条");
                    }
                    excuteInfo = resValidate.toString();

                } catch (Exception e) {
                    excuteInfo = "资源导入失败,请按照模板格式填写！";
                    if (toFile != null) {
                        toFile.delete();
                    }
                } finally {
                    //失败数等于总数 删除导入文件
                    if (importErrorSum == rowsCount && toFile != null) {
                        toFile.delete();
                    }
                }

            }

        }
        Struts2Utils.setRequestAttribute("info", excuteInfo);
        Struts2Utils.setRequestAttribute("resId", Struts2Utils.getParameter("resId"));
        Struts2Utils.setRequestAttribute("viewId", request.getParameter("viewId"));
        return "import";
    }

    public String saveMonitorType() throws Exception {
        String monitorType = request.getParameter("type");
        String selfFlag = request.getParameter("flag");

        MotiRestypeRel rel = new MotiRestypeRel();
        rel.setMoitTypeId(Long.parseLong(monitorType));
        rel.setResTypeId(this.id);
        rel.setSelfFlag(Integer.parseInt(selfFlag));
        resTypeService.saveMonitorTypeRel(rel);
        return null;
    }

    class CompareProperty implements Comparator<Property> {

        /* (non-Javadoc)
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        @Override
        public int compare(Property o1, Property o2) {
            int one = o1.getDisplay().intValue();
            int two = o2.getDisplay().intValue();
            return one - two;
        }

    }
}
